<script setup>
import Footer from "../views/footer.vue";
import {ref, onMounted, computed} from 'vue';
import axios from 'axios';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {UserIcon, ScaleIcon, ArrowUpIcon, CalendarIcon} from '@heroicons/vue/outline';

const router = useRouter();

const showDialog = ref(false);
const form = ref({
  height: '',
  weight: '',
  gender: '',
  age: ''
});

const submitForm = async () => {
  try {
    const username = localStorage.getItem('username');
    form.value.username = username;  // 添加用户名到表单数据
    
    const response = await axios.post('http://localhost:8080/user/update', form.value);
    
    if (response.data === true) {
      // 更新成功
      await fetchUserInfo();  // 刷新用户信息
      showDialog.value = false;  // 关闭对话框
      ElMessage.success('更新成功');
    } else {
      ElMessage.error('更新失败');
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
    ElMessage.error('更新失败');
  }
};

// 定义存储用户信息的响应式数据
const userInfo = ref({
  name: '',
  height: '',
  weight: '',
  gender: '',
  age: ''
});

// 创建获取用户信息的函数
const fetchUserInfo = async () => {
  try {
    const username = localStorage.getItem('username');
    if (!username) {
      router.push('/login');
      return;
    }

    const response = await axios.post('http://localhost:8080/user/info', {
      username: username
    });

    if (response.data.code === 0) {
      userInfo.value = response.data.data;
    } else {
      console.error(response.data.message);
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo();
});

// 添加退出登录功能
const handleLogout = () => {
  localStorage.removeItem('username');
  router.push('/login');
};

// 添加编辑表单的响应式数据
const showEditForm = ref(false);
const editForm = ref({
  height: '',
  weight: '',
  gender: '',
  age: ''
});

// 添加编辑按钮的处理函数
const handleEdit = () => {
  // 复制当前用户信息到编辑表单
  editForm.value = {
    height: userInfo.value.height,
    weight: userInfo.value.weight,
    gender: userInfo.value.gender,
    age: userInfo.value.age
  };
  showEditForm.value = true;
};

// 添加保存编辑的函数
const handleSave = async () => {
  try {
    const username = localStorage.getItem('username');
    const response = await axios.post('http://localhost:8080/user/update', {
      username: username,
      ...editForm.value
    });

    if (response.data.code === 0) {
      // 更新成功后刷新用户信息
      await fetchUserInfo();
      showEditForm.value = false;
    } else {
      console.error(response.data.message);
    }
  } catch (error) {
    console.error('更新用户信息失败:', error);
  }
};

// 添加移动端检测
const isMobile = computed(() => {
  return window.innerWidth <= 768;
});

// 替换 InfoCard 组件的定义
const iconMap = {
  height: ArrowUpIcon,
  weight: ScaleIcon,
  gender: UserIcon,
  age: CalendarIcon
};

const colorMap = {
  blue: 'text-blue-500 bg-blue-50',
  green: 'text-green-500 bg-green-50',
  purple: 'text-purple-500 bg-purple-50',
  orange: 'text-orange-500 bg-orange-50'
};

</script>

<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-400 via-purple-400 to-pink-400 py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-lg mx-auto space-y-8">
      <!-- 个人信息卡片 -->
      <div class="bg-white/90 backdrop-blur-lg rounded-3xl shadow-xl overflow-hidden">
        <!-- 顶部背景装饰 -->
        <div class="h-32 bg-gradient-to-r from-blue-500 to-purple-500 relative">
          <div class="absolute inset-0 bg-white/10 backdrop-blur-sm"></div>
          <!-- 波浪装饰 -->
          <svg class="absolute bottom-0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320">
            <path fill="#ffffff" fill-opacity="0.9" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path>
          </svg>
        </div>

        <!-- 头像区域 -->
        <div class="relative -mt-16 text-center">
          <div class="inline-block p-2 bg-white rounded-full shadow-lg">
            <img class="h-24 w-24 rounded-full object-cover border-4 border-white ring-2 ring-blue-500/20"
                 src="../assets/tx.jpg"
                 alt="用户头像">
          </div>
          <h2 class="mt-4 text-2xl font-bold text-gray-800">
            {{ userInfo.username }}
          </h2>
        </div>

        <!-- 用户信息网格 -->
        <div class="p-6">
          <div class="grid grid-cols-2 gap-4">
            <!-- 替换 InfoCard 组件为普通的 div -->
            <div v-for="(item, index) in [
              {icon: 'height', title: '身高', value: `${userInfo.height} cm`, color: 'blue'},
              {icon: 'weight', title: '体重', value: `${userInfo.weight} kg`, color: 'green'},
              {icon: 'gender', title: '性别', value: userInfo.gender, color: 'purple'},
              {icon: 'age', title: '年龄', value: `${userInfo.age} 岁`, color: 'orange'}
            ]" :key="index" 
              class="bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-all duration-300">
              <div class="flex items-center space-x-3">
                <div :class="`p-2 rounded-lg ${colorMap[item.color]}`">
                  <component :is="iconMap[item.icon]" class="w-5 h-5"/>
                </div>
                <div>
                  <p class="text-sm text-gray-500">{{ item.title }}</p>
                  <p class="text-lg font-semibold text-gray-900">{{ item.value }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮组 -->
      <div class="flex justify-center space-x-4">
        <button @click="showDialog = true"
                class="group relative px-6 py-3 rounded-xl bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all duration-300">
          <span class="relative z-10">编辑资料</span>
          <div class="absolute inset-0 h-full w-full bg-black/10 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300"/>
        </button>
        
        <button @click="handleLogout"
                class="group relative px-6 py-3 rounded-xl bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all duration-300">
          <span class="relative z-10">退出登录</span>
          <div class="absolute inset-0 h-full w-full bg-black/10 rounded-xl opacity-0 group-hover:opacity-100 transition-opacity duration-300"/>
        </button>
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
          v-model="showDialog"
          title="编辑个人资料"
          width="90%"
          custom-class="edit-dialog"
          :close-on-click-modal="false">
        <div class="p-4">
          <el-form :model="form" label-position="top">
            <el-form-item label="身高">
              <el-input-number
                  v-model="form.height"
                  :min="0"
                  :max="300"
                  :precision="1"
                  :step="0.1"
                  controls-position="right"
                  placeholder="请输入身高"
                  class="w-full">
                <template #append>cm</template>
              </el-input-number>
            </el-form-item>

            <el-form-item label="体重">
              <el-input-number
                  v-model="form.weight"
                  :min="0"
                  :max="500"
                  :precision="1"
                  :step="0.1"
                  controls-position="right"
                  placeholder="请输入体重"
                  class="w-full">
                <template #append>kg</template>
              </el-input-number>
            </el-form-item>

            <el-form-item label="性别">
              <el-select v-model="form.gender" placeholder="请选择性别" class="w-full">
                <el-option label="男" value="男"/>
                <el-option label="女" value="女"/>
              </el-select>
            </el-form-item>

            <el-form-item label="年龄">
              <el-input-number
                  v-model="form.age"
                  :min="0"
                  :max="150"
                  controls-position="right"
                  placeholder="请输入年龄"
                  class="w-full">
                <template #append>岁</template>
              </el-input-number>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <div class="flex justify-end space-x-3">
            <el-button @click="showDialog = false" plain>取消</el-button>
            <el-button type="primary" @click="submitForm">保存更改</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <Footer/>
  </div>
</template>

<style scoped>
.backdrop-blur-lg {
  backdrop-filter: blur(16px);
}

/* 编辑对话框样式 */
:deep(.edit-dialog) {
  border-radius: 8px;
  
  .el-dialog__header {
    padding: 16px 20px;
    margin-right: 0;
    border-bottom: 1px solid #e5e7eb;
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    padding: 16px 20px;
    border-top: 1px solid #e5e7eb;
  }
  
  .el-form-item {
    margin-bottom: 20px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-input-number {
    width: 100%;
    
    .el-input__wrapper {
      padding-right: 0;
    }
    
    .el-input-number__decrease,
    .el-input-number__increase {
      border: none;
      background: #f3f4f6;
      
      &:hover {
        color: #409eff;
      }
    }
  }
  
  .el-input__append {
    background: #f3f4f6;
    padding: 0 12px;
    color: #6b7280;
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  :deep(.edit-dialog) {
    width: 90% !important;
    
    .el-dialog__body {
      padding: 16px;
    }
    
    .el-form-item {
      margin-bottom: 16px;
    }
  }
}

/* 按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  
  .el-button {
    min-width: 80px;
  }
}

/* 按钮悬浮效果 */
:deep(.el-button) {
  &.el-button--primary {
    border: none;
    
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1);
    }
  }
}

/* 输入框动画 */
.input-group {
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 0;
    height: 2px;
    background: #60a5fa;
    transition: all 0.3s;
  }
  
  &:focus-within::after {
    width: 100%;
    left: 0;
  }
}

/* 自定义数字输入框样式 */
:deep(.custom-input-number) {
  width: 100%;
  
  .el-input-number__decrease,
  .el-input-number__increase {
    background-color: transparent;
    border: none;
    color: #6b7280;
    
    &:hover {
      color: #3b82f6;
    }
  }
  
  .el-input__wrapper {
    background-color: white;
    box-shadow: none !important;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    padding: 0 12px;
    
    &:hover {
      border-color: #60a5fa;
    }
    
    &.is-focus {
      border-color: #3b82f6;
    }
  }
  
  .el-input__inner {
    height: 44px;
    font-size: 1rem;
    color: #374151;
    
    &::placeholder {
      color: #9ca3af;
    }
  }
  
  /* 隐藏上下箭头 */
  .el-input__inner::-webkit-outer-spin-button,
  .el-input__inner::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  
  /* Firefox */
  .el-input__inner[type=number] {
    -moz-appearance: textfield;
  }
}

/* 修改后缀样式 */
:deep(.el-input__suffix) {
  color: #6b7280;
  font-size: 0.875rem;
  margin-right: 8px;
}

/* 移动端优化 */
@media (max-width: 768px) {
  :deep(.custom-input-number) {
    .el-input__wrapper {
      padding: 0 8px;
    }
    
    .el-input__inner {
      height: 48px;
      font-size: 1.125rem;
    }
  }
}

/* 添加新的动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 波浪动画 */
@keyframes wave {
  0% {
    transform: translateX(0);
  }
  50% {
    transform: translateX(-25%);
  }
  100% {
    transform: translateX(0);
  }
}

.wave {
  animation: wave 10s ease-in-out infinite;
}

/* 卡片悬浮效果 */
.info-card {
  transition: all 0.3s ease;
}

.info-card:hover {
  transform: translateY(-2px);
}
</style>
